package body

import (
	"encoding/json"
	"fmt"
	"gitcode.com/G-YT/iHealth25/server/global"
	"gitcode.com/G-YT/iHealth25/server/model/body"
	bodyRes "gitcode.com/G-YT/iHealth25/server/model/body/response"
	"gitcode.com/G-YT/iHealth25/server/model/common/response"
	"gitcode.com/G-YT/iHealth25/server/utils"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"strconv"
	"strings"
)

type BodyApi struct {
}

// GetBodyAssessPage 获取体态评估页面
// @Tags Body
// @Summary 获取体态评估页面
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query topic.Topic true "获取体态评估页面"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"查询成功"}"
// @Router /body/getBodyAssessPage [get]
func (bodyApi *BodyApi) GetBodyAssessPage(c *gin.Context) {
	uid := utils.GetUserID(c)
	// 获取用户健康管理标签
	bodyInfo, _ := BodyService.GetHealthManageTagByUid(uid, 2)
	// 获取健康管理列表
	bodyList, _ := BodyService.GetHealthManageList()
	// 创建一个新的结构体用来填充
	newBodyList := make([]bodyRes.HealthManage, 0)
	// 填充bb结构体
	for _, v := range bodyList {
		v.Ttids = []uint{}
		tempTtdcount := make([]bodyRes.HealthManageChild, 0)
		for key, value := range v.Ttdcount {
			child := bodyRes.HealthManageChild{
				TtID:  value.TtID,
				Text:  value.Text,
				Value: uint(key),
			}
			// 检查疼痛部位ID是否在Place字段中
			if len(bodyInfo.Place) != 0 {
				ids := strings.Split(bodyInfo.Place, ",")
				for _, id := range ids {
					if id == strconv.Itoa(int(value.TtID)) {
						v.Ttids = append(v.Ttids, uint(key))
						break
					}
				}
			}
			tempTtdcount = append(tempTtdcount, child)
		}
		v.Ttdcount = tempTtdcount
		newBodyList = append(newBodyList, v)
	}
	var painLevels []bodyRes.PainLevel
	var extendData struct {
		Text  string `json:"text"`
		Value int    `json:"value"`
		Color string `json:"color"`
	}
	// 获取疼痛等级字典
	painLevelList, _ := BodyService.GetPainLevelList()
	for _, detail := range painLevelList {
		err := json.Unmarshal([]byte(detail.Extend), &extendData)
		if err != nil {
			fmt.Println("解析JSON失败:", err)
			continue
		}
		IsChoose := false
		detailValue, _ := strconv.ParseUint(detail.Value, 10, 0)
		uintDv := uint(detailValue)
		if bodyInfo.Level == uintDv {
			IsChoose = true
		}
		intDv, _ := strconv.Atoi(detail.Value)
		painLevel := bodyRes.PainLevel{
			Text:     extendData.Text,
			Value:    extendData.Value,
			Color:    extendData.Color,
			Name:     detail.Label,
			ID:       intDv,
			IsChoose: IsChoose,
		}
		painLevels = append(painLevels, painLevel)
	}
	result := bodyRes.BodyAssessResponse{
		TtList: newBodyList,
		Status: bodyInfo.Status,
		Level:  painLevels,
	}
	response.Result(200, result, "获取成功", c)
}

// SaveBodyAssessTag 保存体态评估标签
// @Tags Body
// @Summary 保存体态评估标签
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query body.HealthManageTag true "保存体态评估标签"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"查询成功"}"
// @Router /body/saveBodyAssessTag [post]
func (bodyApi *BodyApi) SaveBodyAssessTag(c *gin.Context) {
	var bh body.HealthManageTag
	err := c.ShouldBindJSON(&bh)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	verify := utils.Rules{
		"PlaceTypes": {utils.NotEmpty()},
		"Place":      {utils.NotEmpty()},
	}
	if err := utils.Verify(bh, verify); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	uid := utils.GetUserID(c)
	bodyInfo, _ := BodyService.GetHealthManageTagByUid(uid, 2)
	// 判断是否存在用户功效标签
	if bodyInfo.ID != 0 {
		if err := BodyService.UpdateHealthManageTag(bodyInfo.ID, &bh); err != nil {
			global.GVA_LOG.Error("保存失败!", zap.Error(err))
			response.FailWithMessage("保存失败", c)
		}
	} else {
		bh.Uid = uid
		bh.Types = 2
		if err := BodyService.CreateHealthManageTag(&bh); err != nil {
			global.GVA_LOG.Error("保存失败!", zap.Error(err))
			response.FailWithMessage("保存失败", c)
		}
	}
	response.Result(200, "", "保存成功", c)
}

// GetBodyBalancePage 获取身体平衡页面
// @Tags Body
// @Summary 获取身体平衡页面
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query body.HealthManageTag true "获取身体平衡页面"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"查询成功"}"
// @Router /body/getBodyBalancePage [get]
func (bodyApi *BodyApi) GetBodyBalancePage(c *gin.Context) {
	id := utils.GetUserID(c)
	if data, err := BodyService.GetBodyBalancePage(id); err != nil {
		global.GVA_LOG.Error("获取失败", zap.Error(err))
		response.FailWithMessage(err.Error(), c)
	} else {
		response.OkWithData(data, c)
	}
}
